package com.xiaoyang.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaoyang.dto.UserDTO;
import com.xiaoyang.helper.DateHelper;
import com.xiaoyang.service.AutoLocationService;
import com.xiaoyang.service.WxPushService;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author guoziyang
 * @create 2020/9/21 9:33 上午
 */

@Service
public class AutoLocationServiceImpl implements AutoLocationService {

    @Autowired
    private WxPushService wxPushService;

    @Value("${CALLBACK_URL}")
    private String CALLBACK_URL;

    private static String SUCCESS = "SUCCESS";

    private static String LEAVE = "LEAVE";

    @Override
    public String submitLocation(UserDTO userDTO) {
        String result = null;
        try {
            String username = userDTO.getUsername();
            String password = userDTO.getPassword();
            String cookie = getCookie(username, password);
            String extension = userDTO.getExtension();
            result = submit(cookie, extension);
            String url = CALLBACK_URL + "/api/logout?uid=" + userDTO.getUid();
            if (LEAVE.equals(result)) {
                wxPushService.wxPush("您已请假，请手动打卡！或" + "<a href=\"" + url + "\">点击退出登录</a>", "UID_" + userDTO.getUid());
            }
            if (SUCCESS.equals(result)) {
                // 发送签到成功消息
                wxPushService.wxPush("您在" + DateHelper.getCurrentTime() + "自动签到成功！" + "<a href=\"" + url + "\">点击退出登录</a>", "UID_" + userDTO.getUid());
            } else {
                wxPushService.wxPush("服务器可能凉了！", "UID_" + userDTO.getUid());

            }
        } catch (Exception e) {
            e.printStackTrace();
            return "FAIL";
        }
        return result;
    }


    /**
     * 获取cookie
     *
     * @return
     */
    @Override
    public String getCookie(String username, String password) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();

        // post方式提交的数据
        FormBody formBody = new FormBody.Builder()
                .add("username", username)
                .add("password", password)
                .build();

        final Request request = new Request.Builder()
                .url("http://localhost:8081/wisedu-unified-login-api-v1.0/api/login")
                .post(formBody)
                .build();

        try {
            Response response = okHttpClient.newCall(request).execute();
            // 判断请求是否成功
            if (response.isSuccessful()) {
                // 服务端返回结果
                String respJson = response.body().string();
                JSONObject jsonObject = (JSONObject) JSONObject.parse(respJson);
                String cookies = jsonObject.getString("cookies");
                return cookies;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 提交请求
     *
     * @param cookie
     * @param extension
     * @return
     */
    private String submit(String cookie, String extension) {
        String CURRENT_DAY = "https://thxy.campusphere.net/wec-counselor-sign-apps/stu/sign/submitSign";

        // 创建一个OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
        // 获取表单Id（如果获取不到表单id可能用户已请假）
        String instanceWid = getInstanceWid(cookie);
        if (instanceWid == null) {
            return "LEAVE";
        }
        // 生成提交json参数
        String submitParams = getSubmitParams(instanceWid);
        // 构造请求体
        RequestBody requestBody = RequestBody.create(submitParams, MediaType.parse("application/json; charset=utf-8"));
        // 创建一个请求对象
        Request request = new Request.Builder()
                .url(CURRENT_DAY)
                .post(requestBody)
                .addHeader("Cookie", cookie)
                .addHeader("Cpdaily-Extension", extension)
                .build();
        // 发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            // 判断请求是否成功
            if (response.isSuccessful()) {
                // 服务端返回结果
                String respJson = response.body().string();
                System.out.println(respJson);
                JSONObject result = (JSONObject) JSONObject.parse(respJson);
                String message = result.getString("message");
                return message;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "FAIL";
    }

    /**
     * 构造提交请求参数
     *
     * @param signInstanceWid
     * @return
     */
    @NotNull
    private String getSubmitParams(String signInstanceWid) {
        String params = "{\n" +
                "\t\"signInstanceWid\": \"1737\",\n" +
                "\t\"longitude\": 113.46269211705885,\n" +
                "\t\"latitude\": 23.262719027016946,\n" +
                "\t\"isMalposition\": 0,\n" +
                "\t\"abnormalReason\": \"\",\n" +
                "\t\"signPhotoUrl\": \"\",\n" +
                "\t\"position\": \"广东省广州市白云区南苑一路\",\n" +
                "\t\"isNeedExtra\": 1,\n" +
                "\t\"extraFieldItems\": [{\n" +
                "\t\t\"extraFieldItemValue\": \"正常\",\n" +
                "\t\t\"extraFieldItemWid\": 573633\n" +
                "\t}]\n" +
                "}";
        JSONObject paramJson = (JSONObject) JSONObject.parse(params);
        paramJson.put("signInstanceWid", signInstanceWid);
        return paramJson.toJSONString();
    }


    /**
     * 获取表单信息
     *
     * @param cookie
     * @return
     */
    private String getInstanceWid(String cookie) {
        String CURRENT_DAY = "https://thxy.campusphere.net/wec-counselor-sign-apps/stu/sign/getStuSignInfosInOneDay";

        HashMap<String, String> signInfo = new HashMap<>();
        // 创建一个OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
        // 创建一个RequestBody(参数1：数据类型 参数2传递的json串)
        RequestBody requestBody = RequestBody.create("{}", MediaType.parse("application/json; charset=utf-8"));
        // 创建一个请求对象
        Request request = new Request.Builder()
                .url(CURRENT_DAY)
                .post(requestBody)
                .addHeader("Cookie", cookie)
                .build();
        // 发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            // 判断请求是否成功
            if (response.isSuccessful()) {
                // 服务端返回结果
                String respJson = response.body().string();
                JSONObject jsonObject = (JSONObject) JSONObject.parse(respJson);
                JSONObject datas = jsonObject.getJSONObject("datas");
                JSONArray tasks = datas.getJSONArray("unSignedTasks");
                if (tasks.size() == 0) {
                    return null;
                }
                JSONObject task = (JSONObject) tasks.get(0);
                String signInstanceWid = task.getString("signInstanceWid");
                return signInstanceWid;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
